#include "mainwindow.h"
#include "ui_mainwindow.h"

#include "mycustomscene.h"
#include "mazecontroller.h"

#include <QSettings>
#include <QMessageBox>
#include <QRegExpValidator>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , maze(nullptr)
    , scene(nullptr)
{
    windowsPositionRead();
    ui->setupUi(this);

    QRegExp regexp("[1-9]|[1-9][0-9]|[1-9][0-9][0-9]");
    ui->lineEdit_1->setValidator(new QRegExpValidator(regexp, this));
    ui->lineEdit_2->setValidator(new QRegExpValidator(regexp, this));

    scene = new MyCustomScene();

    ui->graphicsView->setRenderHint(QPainter::Antialiasing);
    ui->graphicsView->setScene(scene);
    ui->graphicsView->setMouseTracking(true);

    maze = new MazeController(scene);

    connect(scene, &MyCustomScene::signalMouseClickPos, maze, &MazeController::slotMouseClickPos);
    connect(scene, &MyCustomScene::signalMouseMovePos,  maze, &MazeController::slotMouseMovePos);
    connect(this,  &MainWindow::signalSettingsChanged,   maze, &MazeController::slotStartDemo);

}

MainWindow::~MainWindow()
{
    windowsPositionWrite();
    if(maze)    delete maze;
    if(scene)   delete scene;
    delete ui;
}

void MainWindow::windowsPositionRead()
{
    QSettings qsettings("ProSoft", "Maze");
    qsettings.beginGroup("mainwindow");
    move(qsettings.value( "pos", pos() ).toPoint());
    if(qsettings.value( "maximized", isMaximized()).toBool()) showMaximized();
    qsettings.endGroup();
}

void MainWindow::windowsPositionWrite()
{
    QSettings qsettings("ProSoft", "Maze");
    qsettings.beginGroup("mainwindow");
    qsettings.setValue("maximized", isMaximized());
    if(!isMaximized()) qsettings.setValue("pos", pos());
    qsettings.endGroup();
}

void MainWindow::checkSize(QLineEdit *lineEdit)
{
    int size  = lineEdit->text().toInt();
    if(size < 5 or size > 400)
    {
        if(size < 5)    lineEdit->setText("5");
        if(size > 400)  lineEdit->setText("400");
        QMessageBox messageBox;
        messageBox.warning(0, "Warning", "Размер должен быть задан в диапазоне от 5  до 400!");
    }
}

void MainWindow::on_pushButton_clicked()
{
    int width = ui->lineEdit_1->text().toInt();
    int height = ui->lineEdit_2->text().toInt();
    emit signalSettingsChanged(width, height);
    scene->setSceneRect(scene->itemsBoundingRect());
    ui->graphicsView->fitInView(scene->itemsBoundingRect(), Qt::KeepAspectRatio);
}


void MainWindow::on_lineEdit_1_editingFinished()
{
    checkSize(ui->lineEdit_1);
}

void MainWindow::on_lineEdit_2_editingFinished()
{
    checkSize(ui->lineEdit_2);
}
